﻿var zfdxSgmnWidget = LArk.widget.bindClass(LArk.widget.BaseWidget.extend({
    options: {
        resources: ["../../lib/jquery/mCustomScrollbar/jquery.mCustomScrollbar.css", 
        "../../lib/jquery/mCustomScrollbar/jquery.mCustomScrollbar.js",
         "lib/drag.js", "style.css"],
        view: [{
            type: "append",
            url: "view.html"
        }]
    },
    processBar: null,
    create: function () {
        var i = this;
        bindToLayerControl({
            pid: 30,
            name: "污染分析",
            visible: !0,
            onAdd: function () {
                $(i.entities).each(function (t, e) {
                    i.viewer.entities.add(e)
                })
            },
            onRemove: function () {
                $(i.entities).each(function (t, e) {
                    i.viewer.entities.remove(e)
                })
            },
            onCenterAt: function (t) {
                i.viewer.flyTo(i.entities, {
                    duration: t
                })
            }
        })
    },
    winCreateOK: function (t, e) {
        var i = this;
        $("#btn_sgmn_close").click(function (t) {
            i.disableBase()
        }), $("#sb").click(function (t) {
            toastr.info("上报成功")
        }), $(".-l-a-info").mCustomScrollbar({
            theme: "minimal-dark"
        }), $("#sgmn_resultlist_view").mCustomScrollbar({
            theme: "minimal-dark"
        });
        this.processBar = new this._process({
            scale: [0, 20, 40, 60, 80, 100],
            scaleID: "#-process-bottom-scale",
            scaleUnit: "%",
            name:"",
            scaleInit: 0,
            dragContainerID: "#process-bottom-drag",
            containerWidthPX: 453,
            coefficient: 10
        }, function (t, e) {}), $("#btn_sgmn_tsxd").click(function () {
            i.startTsxd()
        }), $("#btn_sgmn_start").click(function () {
            i.isStart ? i.stopPlay() : i.startPlay(!0)
        }), $("#btn_sgmn_back").click(function () {
            $("#view_sgmn_param").show(), $("#view_sgmn_result").hide(), i.stopPlay(), i.iNow = 0, i.clear(), i.setTimeSliderVal(0), i.clearResultLayers()
        }), $("#sgmn_resulttab li").click(function () {
            $(this).parents(".-tabs-ul").children("li").each(function () {
                $(this).removeClass("selected"), $(this.getAttribute("link")).css("display", "none")
            }), $(this).addClass("selected"), "DIV" == $(this.getAttribute("link"))[0].nodeName ? $(this.getAttribute("link")).css("display", "block") : $(this.getAttribute("link")).css("display", "table")
        })
    },
    _process: function (r, n) {
        var o = r.scale.length,
            l = {
                scale: function () {
                    for (var t = "", e = r.scale, i = (r.containerWidthPX / (o - 1)).toFixed(0), s = 0; s < o; s++) s != o - 1 && (t += "<li t=" + r.scale[s] + " style=width:" + i + "px>" + e[s] + r.scaleUnit + "</li>");
                    $(r.scaleID).html(t)
                },
                drag: function () {
                    var a = parseFloat(r.containerWidthPX / ((o - 1) * r.coefficient)),
                        t = a * r.scaleInit,
                        e = '<div class=-process-bar style="width:' + (10 + t) + 'px;"></div><div class=-process-drag style="left:' + t + 'px"></div>';
                    $(r.dragContainerID).html(e), l.changeStyle(r.scaleInit), $(r.dragContainerID).children(".-process-drag").dragging({
                        move: "x",
                        moveHandler: function (t, e) {
                            var i = parseInt((t / a).toFixed(0)),
                                s = $(this).parents("div");
                            s.children(".-process-bar").css("width", t + 10), s.children(".-process-mark").css("left", t), l.changeStyle(i), null != n && n(s, i)
                        }
                    })
                },
                setValue: function (t) {
                    var e = parseFloat(r.containerWidthPX / ((o - 1) * r.coefficient)) * t;
                    $(r.dragContainerID).children(".-process-bar").css("width", 10 + e), $(r.dragContainerID).children(".-process-mark").css("left", e), l.changeStyle(t)
                },
                changeStyle: function (e) {
                    $(r.scaleID).children().each(function (t) {
                        parseInt(this.getAttribute("t")) < e ? $(this).removeClass("-u-gray") : $(this).addClass("-u-gray")
                    })
                }
            };
        return l.scale(), l.drag(), l
    },
    setTimeSliderVal: function (t) {
        this.processBar.setValue(t)
    },
    activate: function () {
        $("#view_sgmn").show(), $("#view_sgmn_timebar").show()
    },
    disable: function () {
        this.stopPlay(), this.clear(), this.markerXY && (this.viewer.entities.remove(this.markerXY), this.markerXY = null), $("#view_sgmn").hide(), $("#view_sgmn_timebar").hide()
    },
    clear: function () {
        var i = this.viewer;
        $(this.entities).each(function (t, e) {
            i.entities.remove(e)
        }), this.entities = [], this.clearResultLayers(), this.viewer.LArkgis.tooltip.close()
    },
    point: null,
    markerXY: null,
    drawHandler: null,
    startTsxd: function () {
        this.endTsxd();
        var a = this;
        this.drawHandler = new Cesium.ScreenSpaceEventHandler(this.viewer.scene.canvas), this.drawHandler.setInputAction(function (t) {
            var e = LArk.point.getCurrentMousePosition(a.viewer.scene, t.position);
            if (e) {
                var i = Cesium.Cartographic.fromCartesian(e),
                    s = {
                        x: Number(Cesium.Math.toDegrees(i.longitude).toFixed(6)),
                        y: Number(Cesium.Math.toDegrees(i.latitude).toFixed(6)),
                        z: Number(i.height.toFixed(1))
                    };
                a.onMapClick_tsxd(s)
            }
        }, Cesium.ScreenSpaceEventType.LEFT_CLICK), $(".cesium-viewer").css("cursor", "crosshair")
    },
    endTsxd: function () {
        null != this.drawHandler && (this.drawHandler.destroy(), this.drawHandler = null, $(".cesium-viewer").css("cursor", ""))
    },
    onMapClick_tsxd: function (t) {
        this.endTsxd(), this.point = t;
        var e = Cesium.Cartesian3.fromDegrees(t.x, t.y, t.z || 0);
        null == this.markerXY ? this.markerXY = this.viewer.entities.add({
            position: e,
            billboard: {
                image: "img/marker/mark1.png",
                horizontalOrigin: Cesium.HorizontalOrigin.CENTER,
                verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
                scale: .6
            }
        }) : this.markerXY.position = e, $("#txt_sgmn_wz").val(t.x + "," + t.y)
    },
    entities: [],
    interval: -1,
    isStart: !1,
    iNow: 0,
    iALLTime: 50,
    iALL: 5,
    startPlay: function (t) {
        if (null != this.point) {
            var e = Number($("#txt_sgmn_fs").val()),
                i = Number($("#txt_sgmn_fx").val()),
                s = Number($("#txt_sgmn_speed").val());
            if (isNaN(e) || 0 == e) layer.tips("请填写有效风速数据", "#txt_sgmn_fs");
            else if (isNaN(i) || i < 0 || 360 < i) layer.tips("请填写有效风向数据(0-360)", "#txt_sgmn_fx");
            else if (isNaN(s) || 0 == s) layer.tips("请填写有效速度数据", "#txt_sgmn_speed");
            else {
                t && (this.iNow = 0, this.clear(), this.setTimeSliderVal(0)), this.isStart = !0, $("#btn_sgmn_start").html("停止模拟"), $("#view_sgmn_param").hide(), $("#view_sgmn_result").show();
                var a = 15 / s,
                    r = this;
                this.interval = setInterval(function () {
                    if (r.iNow++, r.iNow > r.iALL || r.iNow < 0) r.stopPlay();
                    else {
                        var t = r.iNow / r.iALL * r.iALLTime;
                        r.setTimeSliderVal(t), r._addMnCicles(t, e, i,r.iNow)
                    }
                }, 1e3 * a)
            }
        } else toastr.warning("请在图上选择目标点后进行模拟！")
    },
    pausePlay: function () {
        this.isStart && (clearInterval(this.interval), this.isStart = !1)
    },
    stopPlay: function () {
        this.isStart && ($("#btn_sgmn_start").html("开始模拟"), clearInterval(this.interval), this.isStart = !1)
    },
    _last_cicle: null,
    randomColor: ["#f33349", "#f79a2c", "#f2fa19", "#95e40c", "#1ffee6","#f33349","#1630e6"],
    _addMnCicles: function (t, e, i,time) {
        var that = this;
        var s = 60 * t * e / 1e3,
            a = i,
            r = turf.point([this.point.x, this.point.y]),
            n = turf.destination(r, s, a, {
                units: "kilometers"
            });
        n = {
            x: n.geometry.coordinates[0],
            y: n.geometry.coordinates[1],
            z: r.z
        };
        var o = s,
            l = .6 * s,
            u = 90 - i,
            h = this.viewer.entities.add({
                position: Cesium.Cartesian3.fromDegrees(n.x, n.y, n.z),
                ellipse: {
                    show: !0,
                    semiMajorAxis: 1e3 * o,
                    semiMinorAxis: 1e3 * l,
                    rotation: Cesium.Math.toRadians(u),
                    classificationType: Cesium.ClassificationType.BOTH,
                    fill: !0,
                    material: new Cesium.Color.fromCssColorString(""+ that.randomColor[time] +"").withAlpha(.4),
                    outline: !0,
                    outlineColor: new Cesium.Color.fromCssColorString("#ffffff").withAlpha(.7),
                    outlineWidth: 2
                }
            });
        this.entities.push(h),console.log(this.entities), this.viewer.flyTo(h, {
            duration: 2
        }), this.pausePlay();
        var c = (o - l) / 2,
            m = turf.destination(r, c, a, {
                units: "kilometers"
            }),
            d = turf.destination(r, o + l + c, a, {
                units: "kilometers"
            });
        this.queryALL({
            center: n,
            radiusX: 1e3 * o,
            radiusY: 1e3 * l,
            pt1: {
                x: m.geometry.coordinates[0],
                y: m.geometry.coordinates[1]
            },
            pt2: {
                x: d.geometry.coordinates[0],
                y: d.geometry.coordinates[1]
            }
        })
    },
    queryALL: function (t) {
        var e = this;
        this.clearResultLayers();
        var i = "影响范围：";
        t.radiusX < 1e3 ? i += t.radiusX + "米" : i += (.001 * t.radiusX).toFixed(2) + " 公里", $("#lbl_sgmn_tip").html(i);
        var s = !1,
            a = !1;
        this.queryYwData(t, function () {
            (s = !0) && a && e.startPlay()
        }), t.text = "政府机构$医疗$写字楼", this.strartQueryPOI(t, function () {
            a = !0, s && a && e.startPlay()
        })
    },
    clearResultLayers: function () {
        this.clearResult1(), this.clearResult2()
    },
    queryYwData: function (t, e) {
        for (var i = [], s = 0; s < 300; s++) {
            var a = {
                id: s,
                name: "企业" + s,
                x: t.center.x + .1 * Math.random() * (.5 < Math.random() ? 1 : -1),
                y: t.center.y + .1 * Math.random() * (.5 < Math.random() ? 1 : -1)
            };
            i.push(a)
        }
        this.showYwResult(t, i), e()
    },
    showYwResult: function (t, e) {
        var o = this,
            l = ' <tr style="color:black;"><th width="33">序号</th><th>名称</th></tr>',
            u = Cesium.Cartesian3.fromDegrees(t.pt1.x, t.pt1.y),
            h = Cesium.Cartesian3.fromDegrees(t.pt2.x, t.pt2.y),
            c = 2 * t.radiusX,
            m = 0;
        o.objResult1 = {}, $.each(e, function (t, e) {
            var i = Cesium.Cartesian3.fromDegrees(e.x, e.y),
                s = Cesium.Cartesian3.distance(i, u),
                a = Cesium.Cartesian3.distance(i, h);
            if (!(c < s + a)) {
                m++;
                var r = o.viewer.entities.add({
                        position: i,
                        point: {
                            color: new Cesium.Color.fromCssColorString("#3388ff"),
                            pixelSize: 6,
                            outlineColor: new Cesium.Color.fromCssColorString("#ffffff"),
                            outlineWidth: 2,
                            heightReference: Cesium.HeightReference.CLAMP_TO_GROUND
                        },
                        label: {
                            text: e.name,
                            font: "12px Helvetica",
                            style: Cesium.LabelStyle.FILL_AND_OUTLINE,
                            fillColor: Cesium.Color.AZURE,
                            outlineColor: Cesium.Color.BLACK,
                            outlineWidth: 2,
                            horizontalOrigin: Cesium.HorizontalOrigin.CENTER,
                            verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
                            pixelOffset: new Cesium.Cartesian2(0, -10),
                            heightReference: Cesium.HeightReference.RELATIVE_TO_GROUND
                        },
                        tooltip: e.name,
                        data: e
                    }),
                    n = e.id;
                o.objResult1[n] = r, l += " <tr  onclick=\"zfdxSgmnWidget.showDetail1('" + n + "')\" > <td>" + m + "</td>  <td>" + (e.name || "") + "</td></tr>"
            }
        }), $("#sgmn_qc_resulttalbe").html(l), $("#sgmn_qy_count").html(m)
    },
    objResult1: {},
    clearResult1: function () {
        if (this.objResult1) {
            for (var t in this.objResult1) {
                var e = this.objResult1[t];
                this.viewer.entities.remove(e)
            }
            this.objResult1 = {}
        }
    },
    showDetail1: function (t) {
        this.viewer.LArkgis.tooltip.close();
        var e = this.objResult1[t];
        if (null != e) {
            this.viewer.camera.flyTo({
                destination: Cesium.Cartesian3.fromDegrees(e.data.x, e.data.y, 2500),
                duration: 3,
                orientation: {
                    heading: 0,
                    pitch: Cesium.Math.toRadians(-90),
                    roll: 0
                }
            });
            var i = this;
            setTimeout(function () {
                i.viewer.LArkgis.tooltip.show(e, e.position.getValue())
            }, 3e3)
        }
    },
    configBaidu: {
        key: ["bF20kLSGMuRrTRCa3qKkNWIRrwOdyfMv"],
        url: "http://api.map.baidu.com/place/v2/search"
    },
    _key_index: 0,
    getKey: function () {
        var t = this._key_index++ % this.configBaidu.key.length;
        return this.configBaidu.key[t]
    },
    queryParam: {},
    strartQueryPOI: function (t, e) {
        this.queryParam = t, this.thispage = 1, this.queryPOI(e)
    },
    queryPOI: function (e) {
        var i = this,
            t = this.getKey();
        $.ajax({
            url: this.configBaidu.url,
            type: "GET",
            dataType: "jsonp",
            async: !1,
            timeout: "5000",
            contentType: "application/json;utf-8",
            data: {
                output: "json",
                ak: t,
                scope: 2,
                page_size: this.pageSize,
                page_num: this.thispage - 1,
                query: this.queryParam.text || "",
                tag: this.queryParam.type || "",
                location: this.queryParam.center.y + "," + this.queryParam.center.x,
                coord_type: 1,
                radius: this.queryParam.radiusX
            },
            success: function (t) {
                if (0 !== t.status) return toastr.error("请求失败(" + t.status + ")：" + t.message), void(e && e());
                i.showPOIPage(t.results, t.total), e && e()
            },
            error: function (t) {
                toastr.error("请求出错(" + t.status + ")：" + t.statusText), e && e()
            }
        })
    },
    pageSize: 20,
    arrdata: [],
    counts: 0,
    allpage: 0,
    thispage: 0,
    showPOIPage: function (t, e) {
        if (this.arrdata = t, this.counts = e, this.counts < t.length && (this.counts = t.length), this.allpage = Math.ceil(this.counts / this.pageSize), 0 == this.counts);
        else
            for (var i = 0; i < this.arrdata.length; i++) {
                var s = this.arrdata[i],
                    a = (this.thispage - 1) * this.pageSize;
                s.index = a + (i + 1)
            }
        this.showPOIArr(this.arrdata)
    },
    showFirstPage: function () {
        this.thispage = 1, this.queryPOI()
    },
    showNextPage: function () {
        if (this.thispage = this.thispage + 1, this.thispage > this.allpage) return this.thispage = this.allpage, void toastr.info("当前已是最后一页了");
        this.queryPOI()
    },
    showPretPage: function () {
        if (this.thispage = this.thispage - 1, this.thispage < 1) return this.thispage = 1, void toastr.info("当前已是第一页了");
        this.queryPOI()
    },
    showPOIArr: function (t) {
        var h = this,
            c = ' <tr style="color:black;"><th width="33">序号</th><th>名称</th></tr>',
            m = Cesium.Cartesian3.fromDegrees(this.queryParam.pt1.x, this.queryParam.pt1.y),
            d = Cesium.Cartesian3.fromDegrees(this.queryParam.pt2.x, this.queryParam.pt2.y),
            f = 2 * this.queryParam.radiusX,
            g = 0;
        h.clearResult2(), h.objResult2 = {}, $.each(t, function (t, e) {
            var i = e.location.lng,
                s = e.location.lat,
                a = LArk.pointconvert.bd2wgs([i, s]);
            i = a[0], s = a[1], e.x = i, e.y = s;
            var r = Cesium.Cartesian3.fromDegrees(i, s),
                n = Cesium.Cartesian3.distance(r, m),
                o = Cesium.Cartesian3.distance(r, d);
            if (!(f < n + o)) {
                g++;
                var l = h.viewer.entities.add({
                        position: r,
                        point: {
                            color: new Cesium.Color.fromCssColorString("#ffff00"),
                            pixelSize: 6,
                            outlineColor: new Cesium.Color.fromCssColorString("#ffffff"),
                            outlineWidth: 2,
                            heightReference: Cesium.HeightReference.CLAMP_TO_GROUND
                        },
                        label: {
                            text: e.name,
                            font: "12px Helvetica",
                            style: Cesium.LabelStyle.FILL_AND_OUTLINE,
                            fillColor: Cesium.Color.AZURE,
                            outlineColor: Cesium.Color.BLACK,
                            outlineWidth: 2,
                            horizontalOrigin: Cesium.HorizontalOrigin.CENTER,
                            verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
                            pixelOffset: new Cesium.Cartesian2(0, -10),
                            heightReference: Cesium.HeightReference.RELATIVE_TO_GROUND
                        },
                        tooltip: e.name,
                        data: e
                    }),
                    u = e.uid;
                h.objResult2[u] = l, c += " <tr  onclick=\"zfdxSgmnWidget.showDetail2('" + u + "')\" > <td>" + e.index + "</td>  <td>" + (e.name || "") + "</td> </tr>"
            }
        }), c += '<tr> <td colspan="2">  <div class="poipages"> <a href="javascript:zfdxSgmnWidget.showFirstPage()">首页</a> <a href="javascript:zfdxSgmnWidget.showPretPage()">&lt;</a>  <a href="javascript:zfdxSgmnWidget.showNextPage()">&gt;</a> </div> <div class="poipages" style="float:right;">' + this.thispage + "/" + this.allpage + "页 </div></td> </tr>", $("#sgmn_wz_resulttalbe").html(c), $("#sgmn_wz_count").html(g)
    },
    objResult2: {},
    clearResult2: function () {
        if (this.objResult2) {
            for (var t in this.objResult2) {
                var e = this.objResult2[t];
                this.viewer.entities.remove(e)
            }
            this.objResult2 = {}
        }
    },
    showDetail2: function (t) {
        this.viewer.LArkgis.tooltip.close();
        var e = this.objResult2[t];
        if (null != e) {
            this.viewer.camera.flyTo({
                destination: Cesium.Cartesian3.fromDegrees(e.data.x, e.data.y, 2500),
                duration: 3,
                orientation: {
                    heading: 0,
                    pitch: Cesium.Math.toRadians(-90),
                    roll: 0
                }
            });
            var i = this;
            setTimeout(function () {
                i.viewer.LArkgis.tooltip.show(e, e.position.getValue())
            }, 3e3)
        }
    }
}));